import json

import requests


from wx_log.models import *


# Create your views here.
def login(request, *args, **kwargs):
    # 请求微信接口获取openid、session_key
    # @api.route("/v1/wx/login", methods=['GET', 'POST'])
    app_id = request.args.get('app_id')
    app_secret = request.args.get('app_secret')
    code = request.args.get("code")
    wx_url = ("https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={"
              "code}&grant_type=authorization_code").format(
        appId=app_id, appSecret=app_secret, code=code)
    req = requests.get(wx_url)  # wx_url 你要请求的接口地址
    json_text = req.text  # wxUrl接口地址返回的数据字符串
    result_json = json.loads(json_text)  # 将json字符串转换成字典
    result_user = user.objects.filter(user.openid == result_json['openid']).first()
    if result_user is not None:
        json_data = {'id': result_user.id, 'openid': result_user.openid, "avatarUrl": result_user.avatarUrl,
                     "nickName": result_user.nickName,
                     "isBindingMobile": result_user.isBindingMobile}
        result_json = json_data
    else:
        result_json = {"openid": result_json['openid']}
    return result_json

def  userinfo(request):
    if request.method == "GET":
        openid = request.GET.get('openid')
        pwd = request.GET.get('pwd')
        usetlist = User.objects.all()
        for each in usetlist:
            if each.openid == openid and pwd == each.pwd:
                return JsonResponse({'openid': each.openid, 'username': each.username, 'acc': each.acc})
        return JsonResponse({'openid': None, 'username': None, 'acc': None})